import { Button, Form, Input, Result } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { Redirect } from 'react-router'
import { UserInfo } from '../../consts/auth'
import { isAuth } from '../../helpers/auth'
import { SignIn, SignInPayload } from '../../store/actions/auth.actions'
import { AppState } from '../../store/reducers'
import { AuthState } from '../../store/reducers/auth.reducer'
import Layout from './Layout'
const FormList = [
    {
        name: 'password',
        label: '密码',
    },
    {
        name: 'email',
        label: '邮箱',
    },

]
const Signin = () => {
    const auth = useSelector<AppState,AuthState  >(state => state.auth);
    const  dispatch = useDispatch();
    function onFinish(params:SignInPayload) {
        dispatch(SignIn(params))
    }
    function FormComponent() {
        return (<Form onFinish={onFinish}>
            {
                FormList.map(item=>(
                    <Form.Item {...item} key={item.name}>
                        {
                            item.name === 'password' ? <Input.Password /> : <Input />
                        }
                    </Form.Item>
                ))
               
            }
             <Form.Item >
                <Button type="primary" htmlType="submit">
                    登录
                </Button>
            </Form.Item>
        </Form>)
    }

    // 登录失败
    function showError() {
        if(auth.signin.loaded && !auth.signin.success){
            return (
                <Result
                    status="warning"
                    title="登录失败"
                    subTitle={auth.signin.message}
                />
            )
        } 
    }
    // 登录成功
    function loginSuccess() {
        const userData = isAuth();
        if( userData ){
            const {
                user
            } = userData as UserInfo;
            if( user.role === 0 ){ // 普通用户
                return <Redirect to="/user/dashboard"/>
            } else { //  管理员
                return <Redirect to="/admin/dashboard"/>

            }
        }
    }
    return (
        <Layout title="登录" subTitle="">
            {
                showError()
            }
            {
                loginSuccess()
            }
            <FormComponent />
        </Layout>
    )
}

export default Signin
